/*
 * JGO2RDF creates a RDF representation of GAF2 files, which are automatically sourced from GO ftp site.
 * Copyright (C) 2012 Matthew M. Hindle & Artem Lysenko
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package uk.co.jgo2rdf.goa.xrefs;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: mhindle
 * Date: 22/02/12
 * Time: 14:30
 * To change this template use File | Settings | File Templates.
 */
public class XRefParser {

    protected URL url;

    public XRefParser(URL url) {
        this.url = url;
    }

    public XRefParser() throws MalformedURLException {
        url = new URL("ftp://ftp.geneontology.org/pub/go/doc/GO.xrf_abbs");
    }

    /**
     * @return GO official xrefs
     * @throws IOException on accessing the GO.xrf_abbs file
     */
    public Set<XREF> parseXRefs() throws IOException {

        Set<XREF> xrefs = new HashSet<XREF>();

        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url.getHost());
            ftp.login("anonymous", "anonymous");
            ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);

            InputStream stream = ftp.retrieveFileStream(url.getFile());
            try {

                XREF xref = null;

                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    if (line.startsWith("abbreviation:")) {
                        if (xref != null)
                            xrefs.add(xref);
                        String db = line.substring("abbreviation:".length(), line.length());
                        xref = new XREF(db.toUpperCase().trim());
                    } else if (xref != null && line.startsWith("database:")) {
                        String db = line.substring("database:".length(), line.length());
                        if (xref != null) {
                            xref.setDatabase(db.trim());
                        }
                    } else if (xref != null && line.startsWith("generic_url:")) {
                        String generic_url = line.substring("generic_url:".length(), line.length());
                        if (xref != null) {
                            xref.setGeneric_url(generic_url.trim());
                        }
                    } else if (xref != null && line.startsWith("url_syntax:") && xref.getUrl_syntax() == null) {
                        String url_syntax = line.substring("url_syntax:".length(), line.length());
                        int start = url_syntax.lastIndexOf('[');
                        int end = url_syntax.lastIndexOf(']');

                        url_syntax = url_syntax.substring(0, start) +
                                "%s" + url_syntax.substring(end + 1, url_syntax.length());

                        if (xref != null) {
                            xref.setUrl_syntax(url_syntax.trim());
                        }
                    }
                }

            } finally {
                stream.close();
            }

        } finally {
            ftp.disconnect();
        }
        return xrefs;
    }

    public static class XREF {

        public XREF(String abbreviation) {
            this.abbreviation = abbreviation;
        }

        public String getAbbreviation() {
            return abbreviation;
        }

        public void setAbbreviation(String abbreviation) {
            this.abbreviation = abbreviation;
        }

        public String getDatabase() {
            return database;
        }

        public void setDatabase(String database) {
            this.database = database;
        }

        public String getGeneric_url() {
            return generic_url;
        }

        public void setGeneric_url(String generic_url) {
            this.generic_url = generic_url;
        }

        public String getUrl_syntax() {
            return url_syntax;
        }

        public void setUrl_syntax(String url_syntax) {
            this.url_syntax = url_syntax;
        }

        private String abbreviation;
        private String database;
        private String generic_url;
        private String url_syntax;

        public String formatURI(String accession) {
            String result = String.format(url_syntax, accession);
            if (result.equals(url_syntax)) {
                return url_syntax + accession;
            }
            return result;
        }

    }

}
